<template>
  <view>
    <view class="form-row">
      <view class="form-label">采购类型</view>
      <view class="form-value">
        <uni-data-checkbox
          v-model="typeValue"
          :localdata="typeList"
          @change="typeChange"
        />
      </view>
    </view>
    <template v-if="typeValue == 1">
      <view class="form-row">
        <view class="form-label">配件名称</view>
        <view class="form-value">
          <FuzzySearch
            v-model="selectedInventoryId"
            :options="inventoryList"
            display-field1="name"
            display-field2="category.name"
            search-field="name"
            placeholder="请输入配件名称"
            @change="onInventorySelect"
          />
        </view>
      </view>
      <view v-if="inventoryInfo.category" class="form-row">
        <view class="form-label">库存分类</view>
        <view class="form-value">{{ inventoryInfo.category.name || "" }}</view>
      </view>
      <view v-if="inventoryInfo.num" class="form-row">
        <view class="form-label">库存数量</view>
        <view class="form-value">
          <view>{{ inventoryInfo.num || "" }}</view>
          <view class="btn-use" @click="showUse">领用</view>
        </view>
      </view>
      <view v-if="inventoryInfo.address && addressShow" class="form-row">
        <view class="form-label">存放位置</view>
        <view class="form-value">{{ inventoryInfo.address || "" }}</view>
      </view>
      <view v-if="inventoryInfo.image && inventoryInfo.image.length > 0" class="form-row">
        <view class="form-label">图片</view>
        <view class="form-grid">
          <image
            v-for="(item, index) in inventoryInfo.image"
            :key="index"
            :src="item"
            @click="previewImage(item)"
            class="image"
          />
        </view>
      </view>
      <view class="form-row">
        <view class="form-label">采购数量</view>
        <view class="form-value">
          <input
            v-model.trim="num"
            type="number"
            maxlength="10"
            placeholder="请填写采购数量"
          />
        </view>
      </view>
    </template>
    <template v-if="typeValue == 0">
      <view class="form-row">
        <view class="form-label">配件名称</view>
        <view class="form-value">
          <input v-model="inventory_name" type="text" placeholder="请填写配件名称" />
        </view>
      </view>
      <view class="form-row">
        <view class="form-label">配件分类</view>
        <view class="form-value">
          <FuzzySearch
            v-model="category_id"
            :options="categoryList"
            search-field="name"
            placeholder="请选择配件分类"
          />
        </view>
      </view>
      <view class="form-row">
        <view class="form-label">存储类型</view>
        <view class="form-value">
          <uni-data-checkbox
            v-model="cc_type"
            :localdata="cc_typeList"
            @change="cc_typeChange"
          />
        </view>
      </view>
      <template v-if="cc_type == 1">
        <view class="form-row">
          <view class="form-label">请选择库位</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid1"
              :options="kuweiList"
              search-field="name"
              placeholder="请选择库位"
              @change="onPid1Change"
            />
          </view>
        </view>
        <view class="form-row">
          <view class="form-label">请选择盒</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid2"
              :options="heList"
              search-field="name"
              placeholder="请选择盒"
              @change="onPid2Change"
            />
          </view>
        </view>
        <view class="form-row">
          <view class="form-label">请选择层</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid3"
              :options="cengList"
              search-field="name"
              placeholder="请选择层"
              @change="onPid3Change"
            />
          </view>
        </view>
        <view class="form-row">
          <view class="form-label">请选择格</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid4"
              :options="geList"
              search-field="name"
              placeholder="请选择格"
              @change="getAddress"
            />
          </view>
        </view>
      </template>
      <template v-if="cc_type == 2">
        <view class="form-row">
          <view class="form-label">库位</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid5"
              :options="kuweiList"
              search-field="name"
              placeholder="请选择库位"
              @change="onPid1Change"
            />
          </view>
        </view>
        <view class="form-row">
          <view class="form-label">货架</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid6"
              :options="heList"
              search-field="name"
              placeholder="请选择货架"
              @change="onPid2Change"
            />
          </view>
        </view>
        <view class="form-row">
          <view class="form-label">层号</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid7"
              :options="cengList"
              search-field="name"
              placeholder="请选择层号"
              @change="onPid3Change"
            />
          </view>
        </view>
        <view class="form-row">
          <view class="form-label">备注数</view>
          <view class="form-value">
            <FuzzySearch
              v-model="pid8"
              :options="geList"
              search-field="name"
              placeholder="请选择备注数"
              @change="getAddress"
            />
          </view>
        </view>
      </template>
      <view class="form-row">
        <view class="form-label">存放位置</view>
        <view class="form-value">
          <input v-model="address" placeholder="请填写存放位置" />
        </view>
      </view>
      <view class="form-row">
        <view class="form-label">图片</view>
        <view class="form-grid">
          <view
            v-for="(item, index) in imgs_list"
            :key="index"
            style="position: relative"
          >
            <image :src="item" class="image" mode="aspectFill" />
            <image
              src="../../static/del.png"
              mode="widthFix"
              class="del-img"
              @tap="del_img(index)"
            />
          </view>
          <view
            @tap="upImgs"
            style="
              width: 140rpx;
              height: 140rpx;
              background: #f6f7fb;
              border-radius: 8rpx;
              display: flex;
              align-items: center;
              justify-content: center;
            "
          >
            <image
              src="../../static/camera.png"
              mode="widthFix"
              style="width: 60rpx; height: 60rpx"
            />
          </view>
        </view>
      </view>
      <view class="form-row">
        <view class="form-label">采购数量</view>
        <view class="form-value">
          <input v-model.trim="num" type="number" placeholder="请填写采购数量" />
        </view>
      </view>
    </template>
    <button-btm @click="btnJump"> 提交 </button-btm>
    <u-modal
      :show="drawShow"
      title="领用配件"
      showCancelButton
      @confirm="showConfirm"
      @cancel="closeDraw"
    >
      <u--input
        placeholder="请输入领用数量"
        v-model="drawNum"
        border="surround"
        clearable
        type="number"
      />
    </u-modal>
  </view>
</template>

<script>
import buttonBtm from "@/components/button-btm.vue";
import FuzzySearch from "@/components/fuzzy-search/fuzzy-search.vue";
import baseUrl from "@/request/baseUrl.js";
export default {
  components: {
    buttonBtm,
    FuzzySearch,
  },
  data() {
    return {
      warranty_id: null, //工单id

      typeValue: 1, // 采购类型
      typeList: [
        { value: 1, text: "已有库存" },
        { value: 0, text: "无库存" },
      ],

      nameIndex: -1, // 配件名称下标
      inventoryInfo: {}, // 配件详情
      inventoryList: [], // 配件列表
      selectedInventoryId: null, // 选中的配件ID

      addressShow: false, // 显示存放位置

      num: "", // 采购数量

      drawShow: false, // 显示领用弹窗
      drawNum: "", // 领用数量

      category_id: null, // 配件分类id
      inventory_name: "", // 配件名称
      categoryList: [], // 配件分类列表
      cc_type: 1, // 储存类型
      cc_typeList: [
        { value: 1, text: "储物格" },
        { value: 2, text: "货架" },
      ],
      pid1: null, // 库位
      pid5: null, // 库位
      kuweiList: [], // 库位列表
      pid2: null, // 盒
      pid6: null, // 货架
      heList: [], // 盒列表
      pid3: null, // 层
      pid7: null, // 层号
      cengList: [], // 层列表
      pid4: null, // 格
      pid8: null, // 备注数
      geList: [], // 格列表
      address: "", // 地址
      imgs_list: [], // 图片附件
    };
  },
  onLoad(t) {
    this.warranty_id = t.id; //工单id
    this.getList();
    this.getCategoryList();
  },
  methods: {
    // 获取配件列表
    getList() {
      this.$https.post("/warranty/getInventory").then((res) => {
        let list = res.data;
        list.forEach((i) => {
          i.image = i.image.split(",").filter(Boolean);
        });
        this.inventoryList = res.data;
      });
    },
    // 采购类型
    typeChange(e) {
      this.num = "";
      if (this.typeValue == 0) {
        this.cc_type = 1;
        this.category_id = null;
        this.inventory_name = "";
        this.imgs_list = [];
        this.pid1 = null;
        this.pid2 = null;
        this.pid3 = null;
        this.pid4 = null;
        this.pid5 = null;
        this.pid6 = null;
        this.pid7 = null;
        this.pid8 = null;
        this.address = "";
        this.kuweiList = [];
        this.heList = [];
        this.cengList = [];
        this.geList = [];
        this.cc_typeChange();
      } else {
        this.addressShow = false;
        this.selectedInventoryId = null; // 清空选中的配件ID
        this.inventoryInfo = {};
        this.nameIndex = -1;
      }
    },
    // 选择配件
    onInventorySelect(data) {
      this.addressShow = false;
      const item = data.item;
      this.inventoryInfo = item;
      this.nameIndex = this.inventoryList.findIndex((i) => i.id === item.id);
    },
    /* 提交按钮 */
    btnJump() {
      let url = "/warranty/applyPurchase";
      let data = {};
      if (this.typeValue == 1) {
        data = {
          type: this.typeValue, // 采购类型
          inventory_id: this.inventoryInfo.id, // 配件id
          warranty_id: this.warranty_id, //工单id
          num: this.num, // 采购数量
          remark: null,
        };
      } else {
        data = {
          type: this.typeValue, // 采购类型
          cc_type: this.cc_type, // 储存类型 1-储物格 2-货架
          category_id: this.category_id, // 分类id
          inventory_name: this.inventory_name, // 库存名称
          pid1: this.pid1, // 库位
          pid2: this.pid2, // 盒
          pid3: this.pid3, // 层
          pid4: this.pid4, // 格
          pid5: this.pid5, //库位
          pid6: this.pid6, // 货架
          pid7: this.pid7, // 层号
          pid8: this.pid8, // 备注数
          address: this.address, // 地址，要用上面的pid1-pid8拼接出来
          image: this.imgs_list.length ? this.imgs_list.toString() : "", // 图片
          num: this.num, //  采购数量
          warranty_id: this.warranty_id, // 工单ID
          remark: null, // 备注,
        };
      }

      this.$https.post(url, data).then((res) => {
        uni.showToast({
          title: "申请采购成功",
          icon: "none",
          duration: 1500,
        });
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 1500);
      });
    },
    // 领用配件
    showUse() {
      this.drawShow = true;
    },
    // 关闭领用弹窗
    closeDraw() {
      this.drawShow = false;
      this.drawNum = "";
    },
    // 领用配件确认
    showConfirm() {
      if (!this.drawNum) {
        uni.showToast({
          title: "请输入领用数量",
          icon: "none",
          duration: 1500,
        });
        return;
      }
      this.$https
        .get("/inventory/getInventory", {
          inventory_id: this.inventoryInfo.id,
          address: this.inventoryInfo.address,
          num: this.drawNum,
        })
        .then((res) => {
          if (res.code == 1) {
            uni.showToast({
              title: res.msg,
              duration: 1500,
              icon: "none",
            });
            this.addressShow = true;
            this.closeDraw();
            this.getList();
          }
        });
    },
    // 获取配件分类列表
    getCategoryList() {
      this.$https.get("/warranty/getInventoryCategory").then((res) => {
        this.categoryList = res.data;
      });
    },
    // 选择存储类型
    cc_typeChange() {
      // 清空所有相关的选择值
      this.pid1 = null;
      this.pid2 = null;
      this.pid3 = null;
      this.pid4 = null;
      this.pid5 = null;
      this.pid6 = null;
      this.pid7 = null;
      this.pid8 = null;

      // 清空所有相关的选项列表
      this.kuweiList = [];
      this.heList = [];
      this.cengList = [];
      this.geList = [];

      // 清空地址
      this.address = "";
      this.getPidClass({ type: this.cc_type, level: 1, parent_val: null });
    },
    // 选择库位
    onPid1Change(val) {
      this.pid2 = null;
      this.pid3 = null;
      this.pid4 = null;
      this.pid6 = null;
      this.pid7 = null;
      this.pid8 = null;
      this.heList = [];
      this.cengList = [];
      this.geList = [];
      this.getAddress();
      this.getPidClass({ type: this.cc_type, level: 2, parent_val: val.value });
    },
    // 选择盒
    onPid2Change(val) {
      this.pid3 = null;
      this.pid4 = null;
      this.pid7 = null;
      this.pid8 = null;
      this.cengList = [];
      this.geList = [];
      this.getAddress();
      this.getPidClass({ type: this.cc_type, level: 3, parent_val: val.value });
    },
    // 选择层
    onPid3Change(val) {
      this.pid4 = null;
      this.pid8 = null;
      this.geList = [];
      this.getAddress();
      this.getPidClass({ type: this.cc_type, level: 4, parent_val: val.value });
    },
    // 拼接地址
    getAddress() {
      let address = "";
      if (this.cc_type == 1) {
        let name1 = this.kuweiList.find((i) => i.id == this.pid1)?.name || "";
        let name2 = this.heList.find((i) => i.id == this.pid2)?.name || "";
        let name3 = this.cengList.find((i) => i.id == this.pid3)?.name || "";
        let name4 = this.geList.find((i) => i.id == this.pid4)?.name || "";
        address = name1 + name2 + name3 + name4;
      } else {
        let name5 = this.kuweiList.find((i) => i.id == this.pid5)?.name || "";
        let name6 = this.heList.find((i) => i.id == this.pid6)?.name || "";
        let name7 = this.cengList.find((i) => i.id == this.pid7)?.name || "";
        let name8 = this.geList.find((i) => i.id == this.pid8)?.name || "";
        address = name5 + name6 + name7 + name8;
      }
      this.address = address;
    },
    // 获取分类库位列表
    getPidClass(data) {
      this.$https.get("/warranty/pid_class", data).then((res) => {
        if (data.level == 1) {
          this.kuweiList = res.data;
        } else if (data.level == 2) {
          this.heList = res.data;
        } else if (data.level == 3) {
          this.cengList = res.data;
        } else if (data.level == 4) {
          this.geList = res.data;
        }
      });
    },
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        current: url,
        urls: this.inventoryInfo.image,
      });
    },
    // 删除照片
    del_img(i) {
      this.imgs_list.splice(i, 1);
    },
    // 图片上传
    upImgs() {
      const token = uni.getStorageSync("userInfo").token;
      uni.chooseImage({
        count: 9 - this.imgs_list.length,
        sourceType: ["album", "camera"],
        success: (res) => {
          res.tempFilePaths.forEach((filePath) => {
            uni.uploadFile({
              url: `${baseUrl}/common/upload`,
              filePath,
              name: "file",
              formData: { token },
              success: (res1) => {
                try {
                  const data = JSON.parse(res1.data);
                  if (data.code == 1 && data.data?.fullurl) {
                    this.imgs_list.push(data.data.fullurl);
                  } else {
                    uni.showToast({
                      title: data.msg || "上传失败",
                      icon: "none",
                      duration: 1500,
                    });
                  }
                } catch (e) {
                  uni.showToast({ title: "上传失败", icon: "none", duration: 1500 });
                }
              },
              fail: () => {
                uni.showToast({ title: "上传失败", icon: "none", duration: 1500 });
              },
            });
          });
        },
        fail: () => {
          uni.showToast({ title: "选择图片失败", icon: "none", duration: 1500 });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-row {
  padding: 28rpx 32rpx;
  display: flex;
  justify-content: space-between;
  border-bottom: 2rpx solid #f6f7fb;
  .form-label {
    font-size: 28rpx;
    font-weight: 500;
    color: #303030;
  }
  .form-value {
    font-size: 28rpx;
    font-weight: 400;
    max-width: 500rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    text-align: right;
    input {
      font-size: 28rpx;
      font-weight: 400;
      color: #b6bdbd;
    }
    .uni-data-checklist {
      flex: none;
    }
    .btn-use {
      width: 100rpx;
      font-size: 24rpx;
      margin-left: 20rpx;
      background-color: $uni-color-primary;
      text-align: center;
      padding: 8rpx;
      border-radius: 10rpx;
      color: #fff;
    }
  }
  .form-grid {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row-reverse;
    grid-gap: 20rpx;
    max-width: 520rpx;
    .image {
      width: 140rpx;
      height: 140rpx;
      background: #f6f7fb;
      border-radius: 8rpx;
      margin: 0 0 20rpx 20rpx;
    }
    .del-img {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      width: 40rpx;
      height: 40rpx;
      background: #fff;
      border-radius: 50%;
    }
  }
}
</style>
